<!DOCTYPE html>
<html xmlns="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
</head>
<body>
<div>
    <button onclick="connect()" id="connect">连接</button>
    <button onclick="disconnect()" id="disconnect">断开</button>
</div>
<div>
    <input type="text" id="name"/>
    <button id="send">发送</button>
</div>
<div id="msg">

</div>
<script src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
<script src="https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js"></script>

<script>
    var stompClient = null;

    function connect() {
        var socket = new SockJS("/endpoint");//连接SockJS的endpoint名称为"/endpoint"
        stompClient = Stomp.over(socket);//使用STOMP子协议的WebSocket客户端
        stompClient.connect({}, function (frame) {//连接WebSocket服务端
            stompClient.subscribe("/topic/response", function (msg) {//通过stopmClient.subscribe订阅"/topic/response"目标发送的消息，这个路径是在控制器的@SendTo中定义的
                console.log(msg);
                var msgDom = document.getElementById("msg");
                var html = msgDom.innerHTML;
                msgDom.innerHTML = html + "\n" + msg.body;
            });
        });

    }

    function disconnect() {
        if(stompClient!=null){
            stompClient.disconnect();
        }
    }

    function send() {
        var name = document.getElementById("name").value;
        stompClient.send("/message/test", {}, JSON.stringify({//通过stompClient.send向"/message/test"目标发送消息，这个在控制器的@MessageMapping中定义的。
            'msg': name
        }));
    }

    document.getElementById("send").onclick = send;
</script>
</body>
</html>